package com.itcast.cheetah.crr.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.cheetah.crr.product.entity.ProductInfo;
import com.itcast.cheetah.crr.product.mapper.ProductInfoMapper;
import com.itcast.cheetah.crr.product.service.IProductInfoService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ProductInfoServiceImpl
 * @Description: TODO
 * @Date: 2023/3/10
 * @Author: cheetah
 * @Version: 1.0
 */
@Service
@Transactional
@Data
@RequiredArgsConstructor
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper,ProductInfo> implements IProductInfoService {

    private static final String REDIS_PRODUCT_KEY = "product:info:";

    private static final int REDIS_PRODUCT_KEY_EXPIRE = 10*60;//过期时间，我们设置为10分钟

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取商品信息：
     *  先从缓存中查，如果不存在再去数据库中查，然后将数据保存到缓存中
     * @param productInfoId
     * @return
     */
    @Override
    public ProductInfo findProductInfo(Long productInfoId) {
        //1.从缓存中获取商品信息
        Object object = redisTemplate.opsForValue().get(REDIS_PRODUCT_KEY + productInfoId);
        if(ObjectUtil.isNotEmpty(object)){
            return (ProductInfo)object;
        }
        //2.如果缓存中不存在，从数据库获取信息
        ProductInfo productInfo = this.baseMapper.selectById(productInfoId);
        if(productInfo != null){
            //3.将商品信息缓存
            redisTemplate.opsForValue().set(REDIS_PRODUCT_KEY+productInfoId, productInfo,
                    REDIS_PRODUCT_KEY_EXPIRE, TimeUnit.SECONDS);
            return productInfo;
        }
        return null;
    }
}
